#include "GameBase.h"
#include "CCReactor.h"
#include "TcpListener.h"
#include "UdpListener.h"


int CGameBase::TcpListen(const char*ip, uint16_t port)
{
	TcpListener* pListen = new TcpListener(this, 256);
	if (pListen->Listen(ip, port) < 0)
	{// listen err
		delete pListen;
		return -1;
	}

	int iret = CCReactor::Instance()->AttachPoller(pListen);
	if (iret != 0)
	{
		log_boot("Attach epoll Failed. ip=[%s:%d]", ip, port);
		delete pListen;
		return -1;
	}

	return 0;
}

int CGameBase::UdpListen(const char*ip, uint16_t port)
{
	UdpListener* pListen = new UdpListener(this);
	if (pListen->Listen(ip, port) < 0)
	{// listen err
		delete pListen;
		return -1;
	}

	int iret = CCReactor::Instance()->AttachPoller(pListen);
	if (iret != 0)
	{
		log_boot("Attach epoll Failed. ip=[%s:%d]", ip, port);
		delete pListen;
		return -1;
	}

	return 0;
}

CClientHandler* CGameBase::CreateHandler(int netfd, struct sockaddr_in* peer)
{
	return new CClientHandler();
}


int CGameBase::AcceptNewHandler(CClientHandler* pHandler)
{
	static unsigned int flow_id = 0;
	if (++flow_id > 0x7fffffee)
		flow_id = 1;
	pHandler->m_HandlerID = flow_id;
	m_handlerList[flow_id] = pHandler;

	return 0;
}

CClientHandler* CGameBase::GetClientHandler(int handler_id)
{
	CCHandlerMap::iterator iter = m_handlerList.find(handler_id);
	if (iter != m_handlerList.end())
	{
		return iter->second;
	}

	return NULL;
}




















